package com.starblink.library.widget.wishlist

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.starblink.basic.style.R
import com.starblink.android.basic.ext.*
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.databinding.ViewWishlistBoardItemBinding
import com.starblink.rocketreserver.fragment.WishListF

/**
 * 心愿单Board列表项视图
 */
class WishlistBoardItemView @JvmOverloads constructor(
    context: Context,
    attrSet: AttributeSet?,
    defStyleAttr: Int = 0,
) : FrameLayout(context, attrSet, defStyleAttr) {

    private val defaultColor = CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray100)
    private val defaultColorRes = com.starblink.basic.style.R.color.sk_gray100
    private var spmPageValue: Int = 0
    private val binding =
        ViewWishlistBoardItemBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        val typedArray = context.obtainStyledAttributes(
            attrSet,
            R.styleable.PriceView
        )
        binding.laySidesLipDelete.setSwipeEnable(
            typedArray.getBoolean(
                R.styleable.PriceView_pvSwipeEnable,
                true
            )
        )
        typedArray.recycle()
    }

    @SuppressLint("SetTextI18n")
    fun setData(
        showChoiceMode: Boolean = false,
        hasChoice: Boolean = false,
        showSaveBtn: Boolean = false, // 是否显示保存按钮
        wishListItem: WishListF,
        spmPageValue: Int,
        position: Int,
        choiceClickCallback: ((
            isChoice: Boolean,
        ) -> Unit)? = null,
        deleteClickCallback: ((
        ) -> Unit)? = null,
        itemClickCallback: () -> Unit,
    ) {
        this.spmPageValue = spmPageValue
        //多选模式
        if (showChoiceMode) {
            binding.lgChoice.visible()
            if (hasChoice) {
                binding.lgChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_true))
            } else {
                binding.lgChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_false))
            }
            binding.lgChoice.setOnClickListener {
                choiceClickCallback?.invoke(!hasChoice)
            }
        } else {
            binding.lgChoice.gone()
        }

        binding.boardTitle.text = wishListItem.title

        // 用户中心-客态-wishlist-boards-显示保存按钮
        if (showSaveBtn) {
            binding.btnSave.visible()
            binding.layNum.visible()
            binding.itemNum2.text = wishListItem.productCount.toString()
            updateSaveBtn(wishListItem.collectStatus)
            binding.btnSave.click {
                updateSaveBtn(!wishListItem.collectStatus)
                SkGqlClient.defaultLoadingShow(true)
                CommonMutateManage.collectWishlist(
                    context = context,
                    wishList = wishListItem,
                ) {
                    SkGqlClient.defaultLoadingDismiss(true)
                    if (it) {
                        // 收藏或取消收藏成功，更新数据
                        wishListItem.apolloValue("collectStatus", !wishListItem.collectStatus)
                        // 埋点：客态boards页-save按钮
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    spmPageValue,
                                    SpmElementDef.OBJECTIVE_BOARDS_SAVE
                                ),
                                params = mapOf(
                                    "result" to (if (wishListItem.collectStatus) "1" else "0"),
                                    "status" to (if (UserDataCenter.isLogin()) "1" else "0"),
                                )
                            )
                        )
                    } else {
                        // 收藏或取消收藏失败，恢复UI状态
                        updateSaveBtn(wishListItem.collectStatus)
                    }
                }
            }
        } else {
            binding.itemNum1.visible()
            binding.itemNumSuffix1.visible()
            binding.itemNum1.text = wishListItem.productCount.toString()

            if (wishListItem.productCount > 1) {
                binding.itemNumSuffix1.text = "items"
            } else {
                binding.itemNumSuffix1.text = "item"
            }

            if (!wishListItem.description.isNullOrBlank()) {
                binding.desc.visible()
                binding.desc.text = wishListItem.description
            } else {
                binding.desc.gone()
            }
        }

        binding.wishImg1.setImageResource(defaultColorRes)
        binding.wishImg2.setImageResource(defaultColorRes)
        binding.wishImg3.setImageResource(defaultColorRes)
        binding.wishImg4.setImageResource(defaultColorRes)
        binding.wishImg5.setImageResource(defaultColorRes)
        binding.wishImg6.setImageResource(defaultColorRes)
        wishListItem.productList?.let {
            //1
            if (it.isNotEmpty()) {
                ImageUtils.loadImage(context, it[0].productF.mainImg, binding.wishImg1)
            }
            //2
            if (it.size > 1) {
                ImageUtils.loadImage(context, it[1].productF.mainImg, binding.wishImg2)
            }
            //3
            if (it.size > 2) {
                ImageUtils.loadImage(context, it[2].productF.mainImg, binding.wishImg3)
            }
            //4
            if (it.size > 3) {
                ImageUtils.loadImage(context, it[3].productF.mainImg, binding.wishImg4)
            }
            //5
            if (it.size > 4) {
                ImageUtils.loadImage(context, it[4].productF.mainImg, binding.wishImg5)
            }
            //6
            if (it.size > 5) {
                ImageUtils.loadImage(context, it[5].productF.mainImg, binding.wishImg6)
            }
        }

        // 点击Item
        binding.boardLay.click {
            itemClickCallback.invoke()
        }
        binding.boardLay.trackData(
            page = spmPageValue,
            element = SpmElementDef.WishListItemWidget,
            onlyHit = true
        )

        //侧滑删除
        binding.deleteBtn.click {

            ConfirmDialog.Builder(context)
                .setMessage(
                    "Are you sure you want to\n" +
                            "delete this Board?"
                )
                .setCancelButton(com.starblink.basic.style.R.string.cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .setSureButton(com.starblink.basic.style.R.string.delete) { dialog, _ ->
                    dialog.dismiss()
                    deleteClickCallback?.invoke()
                }
                .setCanCancel(false)
                .create().show()
        }
    }

    /**
     * 更新保存按钮状态
     */
    private fun updateSaveBtn(collected: Boolean) {
        binding.btnSave.isSelected = collected
        binding.btnSave.text = if (collected) "Saved" else "Save"
    }
}